package service

import (
	"alarmservice/com"
	"alarmservice/model"
	"errors"
	"strings"
	"time"
)

//主要为中间查询的结构体
type projectGroupNums struct {
	ProjectId int64 `xorm:"pk"`
	Total     int64
}

//根据开始时间和结束时间查询
func GetWarningNumsGroupByProject(projectIds []int64, startTime time.Time, elapsedSecond int) (map[int64]*projectGroupNums, error) {

	if len(projectIds) <= 0 {
		return nil, errors.New("empty params")
	}

	warningNums := make(map[int64]*projectGroupNums)
	endTime := startTime.Add(time.Duration(elapsedSecond) * time.Second)

	projectIdsStr := com.SliceInt64ToSliceString(projectIds)

	err := model.Orm.Sql("select project_id, count(*) as total from warning where project_id in ("+strings.Join(projectIdsStr, ",")+") and create_time >= ? and create_time < ? group by project_id", startTime.Format("2006-01-02 15:04:05"), endTime.Format("2006-01-02 15:04:05")).Find(warningNums)
	if err != nil {
		return nil, err
	} else {
		return warningNums, nil
	}
}

func GetTracingNumsGroupByProject(projectIds []int64) (map[int64]*projectGroupNums, error) {
	if len(projectIds) <= 0 {
		return nil, errors.New("empty params")
	}

	tracingNums := make(map[int64]*projectGroupNums)
	projectIdsStr := com.SliceInt64ToSliceString(projectIds)

	err := model.Orm.Sql("select project_id, count(*) as total from tracing where project_id in (" + strings.Join(projectIdsStr, ",") + ") group by project_id").Find(tracingNums)
	if err != nil {
		return nil, err
	} else {
		return tracingNums, nil
	}
}

func GetTracingEnableNumsGroupByProject(projectIds []int64) (map[int64]*projectGroupNums, error) {
	if len(projectIds) <= 0 {
		return nil, errors.New("empty params")
	}

	tracingNums := make(map[int64]*projectGroupNums)
	projectIdsStr := com.SliceInt64ToSliceString(projectIds)

	err := model.Orm.Sql("select project_id, count(*) as total from tracing where project_id in ("+strings.Join(projectIdsStr, ",")+") and status=? group by project_id", model.StatusNormal).Find(tracingNums)
	if err != nil {
		return nil, err
	} else {
		return tracingNums, nil
	}
}

func GetUserNumsGroupByProject(projectIds []int64) (map[int64]*projectGroupNums, error) {
	if len(projectIds) <= 0 {
		return nil, errors.New("empty params")
	}

	userNums := make(map[int64]*projectGroupNums)
	projectIdsStr := com.SliceInt64ToSliceString(projectIds)

	err := model.Orm.Sql("select project_id, count(*) as total from follow_project where project_id in (" + strings.Join(projectIdsStr, ",") + ") group by project_id").Find(userNums)
	if err != nil {
		return nil, err
	} else {
		return userNums, nil
	}
}
